package org.dromara.iot.config;

import org.dromara.iot.domain.MqttConfigurationProperties;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;

@Configuration
@EnableConfigurationProperties(MqttConfigurationProperties.class)
public class MqttConfiguration {
    @Autowired
    private MqttConfigurationProperties properties;
    @Bean
    public MqttPahoClientFactory  mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setCleanSession(true);
        mqttConnectOptions.setUserName(properties.getUsername());
        mqttConnectOptions.setPassword(properties.getPassword().toCharArray());
        mqttConnectOptions.setServerURIs(new String[]{properties.getUrl()});
        factory.setConnectionOptions(mqttConnectOptions);
        return factory;
    }
}
